package java51.lesson0619;

import java.io.File;
import java.io.FileOutputStream;
import java.util.List;
import java.util.Scanner;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

public class ReviseXml {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		SAXReader reader = new SAXReader();
		try {
			Document doc = reader.read(new File("products.xml"));
			Element root = doc.getRootElement();
			System.out.println("请输入需要修改的商品号：");
			String sch = sc.next();
			System.out.println("请输入需要修改商品的数量：");
			String sum = sc.next();
			List<Element> list = doc.selectNodes("/shop/product");
			for (Element e : list) {
				if ((e.selectSingleNode("itemno").getText()).equals(sch)) {
					e.selectSingleNode("stockcount").setText(sum);

					OutputFormat format = OutputFormat.createCompactFormat();
					format.setEncoding("utf-8");
					XMLWriter xm = new XMLWriter(new FileOutputStream("products.xml"), format);
					xm.write(doc);
					xm.close();
					System.out.println("商品数量修改完成");
					return;
				}
			}
			System.out.println("不存在该编号商品");

		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}